package com.leetcode.leetcode2;

/**
 *  两两交换链表中的节点
 * @author: luhd
 * @create: 2021-09-08
 */
public class Practice24 {
    public static void main(String[] args) {

    }
    public static class ListNode {
       int val;
       ListNode next;
       ListNode() {}
       ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }
    public ListNode swapPairs(ListNode head) {
        // 如果当前节点和下一节点为空，就直接返回       输入[1,2,3,4]    [3,4]
        if(head==null || head.next==null) {
            return head;
        }
        // 将第二个节点以及往后的节点赋值      newHead[2,3,4]          [4]
        ListNode newHead = head.next;
        // newHead.next == head的第三个节点往后   相当于每次递归只处理前两个节点
        // head.next相当于被重新赋值      swapPairs([3,4])
        head.next = swapPairs(newHead.next);    //head[1,3,4]
        //
        newHead.next = head;    // newHead  [2,1,3,4]
        return newHead.next;

        /*
            head:[1,2,3,4]                          head[3,4]
            newHead:[2,3,4]                         newHead:[4]
            head.next = swapPairs([3,4])            head.next[]
                      = [3]                         newHead:[4,3]
         */
    }
}
